package com.wennn.top.security.util;

import com.wennn.top.core.exception.WBusiException;
import com.wennn.top.security.exception.TokenException;
import com.wennn.top.security.model.SessionContext;
import com.wennn.top.security.model.SessionUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.Optional;

@Slf4j
public class ContextUtil {

    /**
     * 获取当前session
     *
     * @author: wennn
     * @date: 5/14/20 9:19 PM
     */
    public static SessionContext getSession() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.isAuthenticated()) {
            if(authentication.getPrincipal() instanceof  SessionContext){
                return (SessionContext) authentication.getPrincipal();
            }else{
                log.error("用户未登陆，无法获取当前上下文");
                throw new TokenException("用户未登陆");
            }
        }
        return null;
    }

    /**
     * 获取当前用户
     * @author: wennn
     * @date: 5/14/20 9:20 PM
     */
    public static SessionUser getUser() {
        return Optional.ofNullable(getSession()).orElseThrow(() -> {
            return new WBusiException("Session 过期");
        }).getSessionUser();
    }

    /**
     * 获取用户id
     * @return
     */
    public static int getUid(){
        return getUser().getId();
    }

    /**
     * 获取权
     * @author: wennn
     * @date: 5/14/20 9:22 PM
     */
    public static Collection getAuthors(){
        return Optional.ofNullable(getSession()).orElseThrow(()->{
            return new WBusiException("Session 过期");
        }).getAuthorities();
    }
}
